package com.gps.skyrc.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RelativeLayout;

import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.github.mikephil.charting.components.Legend;
import com.gps.skyrc.R;
import com.gps.skyrc.activity.base.BaseActivity;
import com.gps.skyrc.adapter.HistoryListAdapter;
import com.gps.skyrc.api.Config;
import com.gps.skyrc.api.EventBusCode;
import com.gps.skyrc.bean.EventBusMessage;
import com.gps.skyrc.bean.HistoryData;
import com.gps.skyrc.data.ParseData;
import com.gps.skyrc.tool.MyTitleBar;
import com.gps.skyrc.tool.PromptDialog;
import com.gps.skyrc.tool.SharedPreferencesUtils;
import com.gps.skyrc.tool.Tip;
import com.gps.skyrc.tool.TwoChooseDialog;
import com.gps.skyrc.tool.logger.ILogger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.function.ToLongFunction;

import butterknife.BindView;

/**
 * Create by ywq
 * 包括请求条目以及每个条目详细信息
 * data 2018/12/12
 */
public class HistoryDataTotalActivity extends BaseActivity implements HistoryListAdapter.CallBack {
    @BindView(R.id.history_total_title)
    MyTitleBar mTitleBar;
    @BindView(R.id.recycle_history_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.history_null_rl)
    RelativeLayout mNullRl;
    private int mOffLine;
    private BleDevice mBleDevice;
    private List<HistoryData> mHistoryData;
    private String mMac;
    private int range = 0;
    private ArrayList<HistoryData> mList;
    private HistoryListAdapter mAdapter;
    private HashMap<Integer, Boolean> mCheckStatue;
    private boolean isHook = false;//是否成全选模式 默认没有选
    private static final int time_out = 10001;
    private int mSize;
    private int mRequestTime;

    @Override
    protected void getLayout() {
        setContentView(R.layout.activity_history_total);
    }

    @Override
    protected void setTitleBar() {
        mTitleBar.initViewsVisible(true, true, true, true, true, true);
        mTitleBar.setAppTitle(getResources().getString(R.string.history_result));
        mTitleBar.setRightTitle(getResources().getString(R.string.management));
        mTitleBar.setOnLeftButtonClickListener(v -> {
            if (isHook) {
                //右边处于删除中，取消删除状态
                isHook = false;
                mTitleBar.setRightTitle(getResources().getString(R.string.management));
                mAdapter.setIsShow(false);
            } else //不处于 直接退出
                onBackPressed();
        });
        mTitleBar.setOnRightButtonClickListener(v -> {
            if (!isHook) {//条目开启选择
                isHook = true;
                mTitleBar.setRightTitle(getResources().getString(R.string.delete));
                mAdapter.setIsShow(true);
            } else {//处于删除中  跳这来 判断是否勾选了再弹提示删除
                if (mCheckStatue.containsValue(true)) {
                    //有勾选  弹提示再删除
                    isHook = false;
                    deleteHint();
                } else {
                    //无勾选  不做任何判断
                    Tip.showToast(mContext, R.string.please_choose_one);
                }
            }
        });

    }

    /**
     * 删除提示
     */
    private void deleteHint() {
        TwoChooseDialog twoChooseDialog = new TwoChooseDialog(mContext, getResources().getString(R.string.delete_hint), getResources().getString(R.string.delete));
        twoChooseDialog.show();
        twoChooseDialog.setClickListener(new TwoChooseDialog.TwoClickListener() {
            @Override
            public void confirm() {
                deleteMsg();
                twoChooseDialog.dismiss();
            }

            @Override
            public void cancel() {
                twoChooseDialog.dismiss();
            }
        });
    }

    /**
     * 删除数据
     */
    private void deleteMsg() {
//        数据库比对删除（包括其他设备的，所以ID要比对），根据时间戳，模式比对
        ArrayList<HistoryData> deleteAfter = new ArrayList<>();//一个新的用来保存删除后还剩下的list
        for (int i = 0; i < mList.size(); i++) {
            if (mCheckStatue.get(i)) {
                mList.get(i).delete();
            } else {
                deleteAfter.add(mList.get(i));
            }
        }

        //排序
        Collections.sort(mList, new Comparator<HistoryData>() {
            @Override
            public int compare(HistoryData o1, HistoryData o2) {
                return (int) (o2.getTimestamp() - o1.getTimestamp());
            }

        });

        //展示删除后的数据
        mCheckStatue.clear();
        for (int k = 0; k < deleteAfter.size(); k++)
            mCheckStatue.put(k, false);

        mList.clear();
        mList.addAll(deleteAfter);
        mAdapter.setDatas(mList, mCheckStatue);
    }

    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void init() {
        mList = new ArrayList<>();
        mCheckStatue = new HashMap<>();
        mHistoryData = LitePal.findAll(HistoryData.class);//所有设备的历史数据总数  需要根据MAC区分，再根据时间戳排序
        mMac = (String) SharedPreferencesUtils.getParam(mContext, SharedPreferencesUtils.PreKey.LAST_DEVICE_MAC, "");
        mOffLine = getIntent().getIntExtra("offLine", 0);
        mAdapter = new HistoryListAdapter(mContext);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.setAdapter(mAdapter);
        if (mOffLine == 1) {
            //在线  数据库当无数据，一直请求下去，保存进数据库  当有数据，每次请求都与数据库当前最新的进行比较
            mBleDevice = getIntent().getParcelableExtra(Config.BLE_SEND_BLEDEVICE);
            //先发data[0]0 data[1]0 从0开始查询 得到第0条的时间戳数据，再发1，再2，再3
            Tip.showLoadDialog(mContext);
            mHandler.sendEmptyMessageDelayed(time_out, 30000);
            getHistoryForCache(range);
        } else {
            //离线
            if (mHistoryData.size() == 0) {//无数据
                mRecyclerView.setVisibility(View.GONE);
                mNullRl.setVisibility(View.VISIBLE);
                mTitleBar.setRightTvVisibility(false);
            } else {
                //分析出属于这个设备的历史数据  以及是否删除掉了再展示
                for (int i = 0; i < mHistoryData.size(); i++) {
                    if (mHistoryData.get(i).getMac().equals(mMac)) {
                        mList.add(mHistoryData.get(i));
                    }
                }
                //排序
                Collections.sort(mList, new Comparator<HistoryData>() {
                    @Override
                    public int compare(HistoryData o1, HistoryData o2) {
                        return (int) (o2.getTimestamp() - o1.getTimestamp());
                    }

                });

                //展示
                for (int i = 0; i < mList.size(); i++)
                    mCheckStatue.put(i, false);

                mAdapter.setDatas(mList, mCheckStatue);

            }
        }

        mAdapter.setCallBackListener(this);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case time_out:
                    Tip.closeLoadDialog();
                    Tip.showToast(mContext, R.string.time_out);
                    break;
            }
        }
    };

    //通过获得历史数据条数来确定设备缓存大小 条数最大50条  还是用2个字节未改
    private void getHistoryForCache(int num) {
        byte[] cmd = {0x0f, 0x06, 0x06, 0, (byte) (num / 256), (byte) (num % 256), 0, 0, (byte) 0xff, (byte) 0xff};
        int checksum = 1;
        for (int i = 2; i < 7; i++)
            checksum += cmd[i];
        cmd[7] = (byte) (checksum & 0xFF);
        BleManager.getInstance().write(mBleDevice, Config.UUID_SERVICE, Config.UUID_WRITE, cmd, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(int current, int total, byte[] justWrite) {
                ILogger.d("获取历史条数成功:" + num);
            }

            @Override
            public void onWriteFailure(BleException exception) {
                Tip.showToast(mContext, R.string.connect_error);
            }
        });
    }

    /**
     * 订阅eventbus事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSubEventBus(EventBusMessage message) {
        int code = message.getCode();
        if (code == EventBusCode.EVENT_BUS_HISTORY_LIST) {

            byte[] data = (byte[]) message.getData();
            mSize = data[4] * 256 + data[5];
            if (mSize == 0) {//返回没有数据,这时查找缓存数据
                showLocalNoDeleteMsg();
            } else {//返回有数据
                mNullRl.setVisibility(View.GONE);
                mRecyclerView.setVisibility(View.VISIBLE);

                HistoryData bean = ParseData.parsehistoryList(data, mMac);

                //分为数据库是否有数据  有就比较  没有就完全请求
                if (mHistoryData.size() == 0) {
                    //数据库没有数据
                    mList.add(bean);
                    check(mSize);
                } else {
                    //数据库有数据
                    //这个设备的数据库
                    if (mList.size() == 0) {//把数据库中属于这个MAC地址的数据全部取出
                        for (int i = 0; i < mHistoryData.size(); i++) {
                            if (mHistoryData.get(i).getMac().equals(mMac)) {
                                mList.add(mList.size(), mHistoryData.get(i));
                            }
                        }
                    }
                    if (mList.size() != 0) {
                        //数据库有这个设备的数据
                        long zero = 0;
                        long timestamp = (long) SharedPreferencesUtils.getParam(mContext, mMac + SharedPreferencesUtils.PreKey.GET_SUCCESS_DATA_TOTAL_TIMESTAMP, zero);
                        boolean haveSame = false;
                        //表明本次拿到的数据的时间戳比保存在本地的要大，表明为新数据；否则则为老数据，不再次请求
                        if (timestamp > bean.getTimestamp())
                            haveSame = true;

                        if (haveSame) {
                            //表明已经在数据库中
//                            for (int i = 0; i < mList.size(); i++)
//                                mCheckStatue.put(i, false);
//
//                            mHandler.removeMessages(time_out);
//                            Tip.closeLoadDialog();
//                            LitePal.saveAll(mList);
//                            mAdapter.setDatas(mList, mCheckStatue);
//                            SharedPreferencesUtils.setParam(mContext, mMac + SharedPreferencesUtils.PreKey.GET_SUCCESS_DATA_TOTAL_TIMESTAMP, System.currentTimeMillis() / 1000);
//                            ILogger.d("have" + mList.size());
                            showMsg();
                        } else {
                            //表明为新数据  添加
                            mList.add(range, bean);
                            range++;
                            //比较请求次数是否和设备数据数量一致  一致就不请求
                            if (mSize == range) {
                                showMsg();
                            } else
                                getHistoryForCache(range);
                        }
                    } else {
                        //数据库没有有这个设备的数据
                        //表明为新数据  添加
                        mList.add(0, bean);
                        range++;
                        //比较请求次数是否和设备数据数量一致  一致就不请求
                        if (mSize == range) {
                            showMsg();
                        } else
                            getHistoryForCache(range);

                    }

                }

            }
        }else if (code == EventBusCode.EVENT_BUS_READ_DATA) {
            byte[] data = (byte[]) message.getData();
            ParseData.parseHistoryDetail(data, mList.get(mRequestTime));
            mRequestTime++;
            if (mRequestTime < mSize)
                getDetailMsg(mRequestTime);
            else {
                Tip.closeLoadDialog();
                LitePal.saveAll(mList);
            }
        }
    }

    private void showMsg(){

        //排序
        Collections.sort(mList, new Comparator<HistoryData>() {
            @Override
            public int compare(HistoryData o1, HistoryData o2) {
                return (int) (o2.getTimestamp() - o1.getTimestamp());
            }

        });

        for (int i = 0; i < mList.size(); i++)
            mCheckStatue.put(i, false);

        mHandler.removeMessages(time_out);
        Tip.closeLoadDialog();
        LitePal.saveAll(mList);
        mAdapter.setDatas(mList, mCheckStatue);
        SharedPreferencesUtils.setParam(mContext, mMac + SharedPreferencesUtils.PreKey.GET_SUCCESS_DATA_TOTAL_TIMESTAMP, System.currentTimeMillis() / 1000);
        ILogger.d("have" + mList.size());



        if (mSize != 0) {
            Tip.showLoadDialog(mContext);
            mRequestTime = 0;
            getDetailMsg(mRequestTime);
        }
    }

    //获得详细的数据
    private void getDetailMsg(int index) {
        byte[] cmd = {0x0f, 0x05, 0x07, 0, 0, 0, 0, (byte) 0xff, (byte) 0xff};
        int historyDetailId = mList.get(index).getHistoryDetailId();
        cmd[4] = (byte) (historyDetailId & 0xFF);
        int checksum = 1;
        for (int i = 2; i < 6; i++)
            checksum += cmd[i];
        cmd[6] = (byte) (checksum & 0xFF);
        BleManager.getInstance().write(mBleDevice, Config.UUID_SERVICE, Config.UUID_WRITE, cmd, new BleWriteCallback() {
            @Override
            public void onWriteSuccess(int current, int total, byte[] justWrite) {
                Tip.closeLoadDialog();
                ILogger.d("请求成功");
            }

            @Override
            public void onWriteFailure(BleException exception) {
                Tip.closeLoadDialog();
                Tip.showToast(mContext, R.string.send_error);
            }
        });
    }

    private void showLocalNoDeleteMsg() {
        for (int i = 0; i < mHistoryData.size(); i++) {
            if (mHistoryData.get(i).getMac().equals(mMac)) {
                mList.add(mList.size(), mHistoryData.get(i));
            }
        }

        if (mList.size() != 0) {
            showMsg();
        } else {
            //没有任何数据
            Tip.closeLoadDialog();
            mHandler.removeMessages(time_out);
            mRecyclerView.setVisibility(View.GONE);
            mNullRl.setVisibility(View.VISIBLE);
            mTitleBar.setRightTvVisibility(false);
        }

    }

    private void check(int size) {
        if (size == (range + 1)) {//size 1  range为0时也是有1条数据
            //获取数据完成
            //保存数据
            showMsg();
        } else {
            range++;
            ILogger.d("range:" + range);
            getHistoryForCache(range);
        }
    }

    @Override
    public void onMoreItemClick(HashMap<Integer, Boolean> checkStatue) {
        this.mCheckStatue = checkStatue;
    }

    @Override
    public void onSingleItemClick(HistoryData bean) {
            Bundle bundle = new Bundle();
            bundle.putInt("isOnOff", mOffLine);
            bundle.putString("which", "history");
            if (mOffLine == 1)
                bundle.putParcelable(Config.BLE_SEND_BLEDEVICE, mBleDevice);
            bundle.putParcelable(Config.HISTORY_SINGLE_DATA, bean);
            startActivity(TestDetailActivity.class, bundle);
    }
}
